'use strict'
const { exec,setCmdStr } = require("./execCmd");
const APPLICATION = require("./Application");
const {   
  getFileLists,
  getFiles,
  isDir,
  isFile,
  getFileContent,
  createDir,
  joinPath
} = require("./fileASys");

let times = 0;

main(APPLICATION.sourceDir);
function main(path) {
  // 先获取所有视频分类（避免一个视频里面有多个缓存结果）
  let parentsFiles = getFileLists(path);
  // console.log(parentsFiles);
  parentsFiles.map( (videoDir,index) => {
    if(index > 0) {
      let childFiles = getFileLists(joinPath(path,videoDir));
      // console.log(childFiles);
      // 判断是否包含多集
      if(childFiles.indexOf(APPLICATION.entry) == -1) {
        childFiles.map( (val,i) => {
          console.log("child: " + times + "、" + videoDir);
          let files = getFileLists(joinPath(path,videoDir,val),true)
          // console.log(files);
          let entryInfo = getEntryInfo(files,APPLICATION.entry);
          createVideo(entryInfo,files);
          ++times;
        })
      }else {
        console.log("current: " + times + "、" + videoDir);
        let entryInfo = getEntryInfo(childFiles,APPLICATION.entry);
        createVideo(entryInfo,childFiles);
        ++times;
      }
    }
  })
}
/**
 * 转换为MP4
 * @param {String[]} m4sFiles    m4s文件地址 
 * @param {String} resultName  生成的结果名称（不带后缀名；后缀名在配置文件中指定）
 * @returns 
 */
function changeToMp4(m4sFiles=[],resultName) {
  if(m4sFiles instanceof Array) {
    let mp3 = "",mp4 = "";
    if(m4sFiles.length == 0) {
      return ;
    }else if(m4sFiles.length == 1) {
      mp3 = m4sFiles.pop();
    }else if(m4sFiles.length == 2) {
      mp3 = m4sFiles.pop();
      mp4 = m4sFiles.pop();
    }
    let fileName = resultName+APPLICATION.resultFileType;
    // 同名文件存在时则不生成
    if(!isFile(fileName)) {
      let params = setCmdStr(mp3,mp4,fileName);
      exec(params);
    }else {
      console.log("\t" + resultName + " file exist !");
    }
  }
}

/**
 * 生成video
 * @param {Object} entryInfo  entry 文件内容 
 * @param {String[]} files            文件列表
 */
function createVideo(entryInfo={},files=[]) {
  let m4sFiles = getM4sFile(files);
  // console.log(m4sFiles);
  let dirFieldName = entryInfo[APPLICATION.entryFields.dirFieldName];
  // 视频的标题不能为空并且m4s文件也至少有一个才能转换
  if(dirFieldName && m4sFiles.length > 0) {
    let dir = joinPath(APPLICATION.saveDir,setFileFormat(dirFieldName));
    // console.log(setFileFormat(dirFieldName));
    createDir(dir);
    let videoName = setFileFormat(APPLICATION.entryFields.videoFieldName(entryInfo));
    // console.log(videoName);
    changeToMp4(m4sFiles,joinPath(dir,videoName));
  }else {
    console.log("no video:  ",files);
  }
}
/**
 * 格式化字符串-避免文件名异常字符冲突
 * @param {String} str 
 * @returns {String}
 */
function setFileFormat(str) {
  return str
    .replace(/\\/g,"、")
    .replace(/\//g,"、")
    .replace(/(\|)/g,"-")
    .replace(/&/g,",")
    .replace(/ /g,"_");
}

// 获取m4s视频文件目录
function getM4sFile(fileList=[]) {
  let result = fileList.filter( v => v.indexOf(APPLICATION.m4s) != -1);
  return result;
}

/**
 * 获取入口文件相关信息 转换为json
 * @param {String[]} files 
 * @param {String} entry 
 * @returns {Map<String,Object>}
 */
function getEntryInfo(files=[],entry="") {
  let entryFileName = files.filter( v => v.indexOf(entry) != -1 );
  if(entryFileName.length > 0) {
    let content = getFileContent(entryFileName.pop());
    return (JSON.parse(content));
  }
}